package me.xinping.libs.utils

import java.util.*
import java.util.concurrent.atomic.AtomicInteger

/**
 * 对Timer的简单封装的计数器.
 * <p>
 * Date 2018/12/4
 * @author fanxinping_cd@keruyun.com
 */
class CountTimer {
    private var countTimer: Timer? = null
    private var countTimerTask: TimerTask? = null
    private val timeCount: AtomicInteger = AtomicInteger(0)

    fun start(delay: Long = 0L, period: Long = 1_000L, runAction: (Int) -> Unit) {
        stop()
        countTimer = Timer()
        countTimerTask = object : TimerTask() {
            override fun run() {
                runAction.invoke(timeCount.incrementAndGet())
            }
        }
        countTimer?.schedule(countTimerTask, delay, period)
    }

    fun stop() {
        timeCount.set(0)
        countTimerTask?.cancel()
        countTimer?.cancel()
        countTimer?.purge()
    }
}